# -*- coding: utf-8 -*-

# $Id: app.py 2 2012-09-01 15:54:17Z alexis.roda.villalonga@gmail.com $

import glob
import os
import re

import django

from dja_skel.skeletons.base import BaseProjectSkel


_INSTALLED_APPS = "INSTALLED APPLICATIONS"
_INSTALLED_APPS_RE = re.compile("-*- %s -*-" % _INSTALLED_APPS)


class DjangoApplication(BaseProjectSkel):
    variables = ("appname", )
    skeleton_path = 'templates/app'
    summary = 'Skeleton for a django app.'

    def after_instantiation(self):
        super(DjangoApplication, self).after_instantiation()
        self._add_to_installed_apps()
        self._add_to_project_urls()
        self._install_python_package()

    def _add_to_installed_apps(self):
        """Adds the app to INSTALLED_APPS.

        This method looks for the marker in all files matching the
        shell pattern 'settings*.py'. This way developer is not
        constrained to the initial layout of the project as generated
        by 'dja_skel'.
        """
        prj_root = self.project.root
        for path in glob.glob(os.path.join(prj_root, "settings*.py")):
            rel_path = path[len(prj_root) + 1:]
            settings = self.project.get_file(rel_path)
            if settings.find_line_containing(_INSTALLED_APPS_RE):
                settings.insert_before(
                    ['"{}",\n'.format(self._context["appname"])],
                    _INSTALLED_APPS
                    )
                settings.save()

    def _install_python_package(self):
        """Installs the app in development mode.
        """
        pkg_root = os.path.join(self._dest_dir, self._context["appname"])
        cwd = os.getcwd()
        os.chdir(pkg_root)
        os.system("python setup.py develop")
        os.chdir(cwd)

    def _add_to_project_urls(self):
        """Adds an entry for the app in 'project.urls'
        """
        urls = self.project.get_file("urls.py")
        url_pattern = 'url(r"^{appname}/", include("{appname}.urls")),\n'.format(
            appname=self._context["appname"]
            )
        urls.insert_before([url_pattern], "APPLICATION URLS")
        urls.save()
